package bp.wf.minio;

import bp.da.DataType;
import bp.da.Log;
import bp.da.LogType;
import bp.sys.FrmAttachmentDB;
import io.minio.*;
import io.minio.errors.*;
import io.minio.http.Method;
import okhttp3.OkHttpClient;
import org.apache.http.util.TextUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.net.ssl.*;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class MinioHelper {

    private static  MinioClient minioClient;


    public  static  String host="";
    public  static  String accessKey="";
    public  static  String secretKey="";
    public  static  String bucket="";

    public  MinioHelper(){

    }

    static {


//        if (minioClient == null) {
//            try {
//                host = bp.difference.SystemConfig.getAppSettings().get("minio_host").toString();
//                accessKey = bp.difference.SystemConfig.getAppSettings().get("minio_accessKey").toString();
//                secretKey = bp.difference.SystemConfig.getAppSettings().get("minio_secretKey").toString();
//                bucket = bp.difference.SystemConfig.getAppSettings().get("minio_bucket").toString();
//                OkHttpClient okHttpClient = getUnsafeOkHttpClient();
//                minioClient = MinioClient.builder()
//                        .endpoint(host)
//                        .credentials(accessKey, secretKey).httpClient(okHttpClient).build();
//            } catch (Exception ex) {
//                System.out.println(ex);
//                Log.DefaultLogWriteLine(LogType.Error, ex.getMessage());
//            }
//        }
    }
    public boolean  ceshi(){

        for(int i=0;i<2;i++){
            if(i==0){
                return false;
            }
        }
         return false;
    }
    public static   String putObject(MultipartFile multipartFile,String savePath) throws Exception {
        // bucket 不存在，创建
        try (InputStream inputStream = multipartFile.getInputStream()) {
            // 上传文件的名称
            String fileName = savePath+multipartFile.getOriginalFilename();
            PutObjectArgs args = PutObjectArgs.builder()
                    .bucket(bucket)
                    .object(fileName)
                    .stream(inputStream, multipartFile.getBytes().length, -1)
                    .contentType(multipartFile.getContentType())
                    .build();
            minioClient.putObject(args);
            // 返回访问路径
            return host+"/"+bucket+"/"+fileName;
        }catch (Exception ex){
            ex.printStackTrace();
            Log.DefaultLogWriteLine(LogType.Error,ex.getMessage());
            throw  ex;
        }
    }

    /***
     * 判断文件是否存在
     * @param objectName
     * @return
     */
    public static boolean isObjectExist(String objectName) {
        boolean exist = false;
        try {
            exist=minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucket).build());
        } catch (Exception e) {
            System.out.println(e);
            Log.DefaultLogWriteLine(LogType.Error,e.getMessage());
        }
        return exist;
    }
    /**
     * 文件下载
     */
    public  static  void download(String fileUrl, String contentType, String filePath) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        // 从链接中得到文件名
        InputStream inputStream;
        try {
            inputStream=minioClient.getObject(GetObjectArgs.builder().bucket(bucket).object(fileUrl).build());

            OutputStream outStream = new FileOutputStream(filePath);
                byte[] buffer = new byte[4096];
                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outStream.write(buffer, 0, bytesRead);
                }
        } catch (Exception e){
            e.printStackTrace();
            Log.DefaultLogWriteLine(LogType.Error,e.getMessage());
            throw e;
        }
    }

    /***
     * 获取预授权预览url
     * @param objectName
     * @return
     * @throws Exception
     */
    public  static  String getPresignedObjectUrl(String objectName) throws Exception {
        try {
            Map<String, String> reqParams = new HashMap<String, String>();
            reqParams.put("response-content-type", "image/jpeg");

            return minioClient.getPresignedObjectUrl(
                    GetPresignedObjectUrlArgs.builder()
                            .method(Method.POST)
                            .bucket(bucket)
                            .object(objectName)
                            .expiry(60 * 60 * 24)
                            .extraQueryParams(reqParams)
                            .build());
        } catch (Exception e) {
            throw new Exception(e);
        }
    }

    public  static void  main(String[] args)  {

           try{
               OkHttpClient okHttpClient = getUnsafeOkHttpClient();
               MinioClient minioClient = MinioClient.builder().endpoint("https://172.19.144.11:9082")
                       .credentials("Minio", "Abc_123!@#").httpClient(okHttpClient).build();
               //minioClient = new MinioClient("https://172.19.144.11:9082", Integer.parseInt("9082"),"Minio", "Abc_123!@#",(String)null,false,okHttpClient);
               File file = new File("D:\\1.txt");
//            InputStream inputStream = new FileInputStream(file);
//            PutObjectArgs args = PutObjectArgs.builder()
//                    .bucket(bucketName)
//                    .object(objectName)
//                    .stream(inputStream, file.length(), -1)
//                    .contentType("txt")
//                    .build();
//            minioClient.putObject(args);

           }catch (Exception ex){
               ex.printStackTrace();
           }

    }

    /***
     * 判断桶是否存在
     * @param bucketName
     * @return
     */
    public boolean existsBucket(String bucketName) {
        try {
            minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
        } catch (Exception e) {
            return false;
        }
        return true;
    }
    public static OkHttpClient getUnsafeOkHttpClient() {
        try {
            final TrustManager[] trustAllCerts = new TrustManager[]{
                    new X509TrustManager() {
                        @Override
                        public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) {
                        }

                        @Override
                        public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) {
                        }

                        @Override
                        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                            return new java.security.cert.X509Certificate[]{};
                        }
                    }
            };
            final SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
            final javax.net.ssl.SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
            OkHttpClient.Builder builder = new OkHttpClient.Builder();
            builder.sslSocketFactory(sslSocketFactory,(X509TrustManager)(trustAllCerts[0]));
            builder.hostnameVerifier(new HostnameVerifier() {
                //这里存放不需要忽略SSL证书的域名，为空即忽略所有证书
                String[]ssls = {};
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    if (TextUtils.isEmpty(hostname)) {
                        return false;
                    }
                    return !Arrays.asList(ssls).contains(hostname);
                }
            });

            OkHttpClient okHttpClient = builder.connectTimeout(10, TimeUnit.MINUTES).
                    writeTimeout(10, TimeUnit.MINUTES).readTimeout(10, TimeUnit.MINUTES).retryOnConnectionFailure(true).build();
            return okHttpClient;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
